<template>
    <div class="bg-black w-screen h-screen text-white">
        <header class="text-center">
            <h1 class="text-4xl font-bold  mb-4">{{ pageTitle }}</h1>
            <div class="flex items-center justify-center gap-4 text-sm">
                <span> 版本：{{ version }}</span>
                <span>|</span>
                <span>作者：{{ author }}</span>
                <button class="meta-btn px-3 py-1 bg-green-500 text-black  rounded hover:bg-gray-300"
                    @click="showAbout = true">说明</button>
            </div>
        </header>

        <div id="content" class="flex h-[calc(100vh-120px)] mt-4 relative">
            <!-- 浮动切换按钮 -->
            <button
                class="absolute left-0 top-4 z-10 p-2 bg-blue-600 text-black rounded-r-lg shadow-lg hover:bg-blue-700 transition-all duration-300"
                @click="toggleResourcePanel">
                {{ showResourcePanel ? '◀' : '▶' }}
            </button>
            <!-- 资源面板 -->
            <aside id="left" v-if="showResourcePanel"
                class="left rounded-lg border border-gray-300 overflow-auto min-w-64 max-w-96 flex flex-col h-full bg-slate-800 transition-all duration-300">
                <h3 class="text-center">模块节点</h3>

                <div id="directory-selector" class="text-center my-4">
                    <button
                        class="select-dir-btn bg-blue-600 text-black rounded-lg px-4 py-2 hover:bg-blue-700 transition-colors"
                        @click="selectDirectory">
                        选择Mods目录
                    </button>
                    <div v-if="selectedDirectory !== ''" class="px-2 break-all whitespace-pre-wrap">
                        <span>{{ selectedDirectory }}</span>
                    </div>
                </div>

                <!-- Mods资源表展示 -->
                <div id="left-body" class="flex flex-col flex-1 min-h-0">
                    <div id='mods-resource-table' v-if="resourceTableData.mods.length > 0"
                        class="bg-black flex-1 my-2 overflow-auto">
                        <div id="resource-tree">
                            <div id="resource-root">
                                <div id="mods-root" class="cursor-pointer hover:bg-gray-700 transition-colors"
                                    @click="modsRootExpanded = !modsRootExpanded">
                                    <span>{{ modsRootExpanded ? '▼' : '▶' }}</span>
                                    <span>Mods</span>
                                </div>

                                <div v-if="modsRootExpanded" id="mods" class="pl-4">
                                    <!--Mods节点-->
                                    <div v-for="mod in resourceTableData.mods" :key="mod.modName">
                                        <div class="resource-mod-header cursor-pointer hover:bg-gray-700 transition-colors"
                                            @click="toggleModExpansion(mod)">
                                            <span class="expand-icon">{{ mod.expanded ? '▼' : '▶' }}</span>
                                            <span v-if="mod.prefixLabel" class="mod-label">{{ mod.prefixLabel }}</span>
                                            <span class="mod-name">{{ mod.modName }}</span>
                                            <span v-if="mod.affixLabel" class="mod-label">{{ mod.affixLabel }}</span>
                                        </div>
                                        <!--我们这里规定一个Mod展开后只有一个层级-->
                                        <div v-if="mod.expanded && mod.resources.length > 0" class="pl-4">
                                            <div v-for="resource in mod.resources" :key="resource.name"
                                                class="resource-item">
                                                <div class="resource-item-header cursor-pointer hover:bg-gray-700 transition-colors"
                                                    @click.stop="handleResourceClick(resource)">
                                                    <span v-if="resource.prefixLabel" class="resource-label">{{
                                                        resource.prefixLabel
                                                    }}</span>
                                                    <span class="resource-name">{{ resource.name }}</span>
                                                    <span v-if="resource.affixLabel" class="resource-label">{{
                                                        resource.affixLabel
                                                    }}</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </aside>

            <main id="center"
                class="center rounded-lg border border-gray-300 flex-1 bg-slate-800 flex flex-col overflow-hidden">
                <ItemStringPanel ref="itemStringPanelRef" v-if="currentResourceItem?.type === 'ItemStrings'"
                    :resourceItem="currentResourceItem" :tauriConfig="appTauriConfig"  />
                <TextPanel v-else :resourceItem="currentResourceItem" />
            </main>


        </div>

        <div v-if="showAbout" class="fixed inset-0 z-50 flex items-center justify-center"
            @click.self="showAbout = false">
            <div class="w-2/3 h-2/3 border border-white bg-black text-white rounded-lg shadow-xl overflow-hidden">
                <div class="flex items-center justify-between px-4 py-2 border-b border-white/20">
                    <h2 class="text-xl font-semibold">关于本工具</h2>
                    <button class="px-2 py-1 text-black bg-white rounded hover:bg-gray-200"
                        @click="showAbout = false">×</button>
                </div>
                <div class="p-4 h-[calc(100%-88px)] overflow-auto bg-gray-900 text-white">
                    <p>{{ aboutText }}</p>
                </div>
                <div class="px-4 py-2 border-t border-white/20 flex justify-end">
                    <button class="px-3 py-1 bg-white text-black rounded hover:bg-gray-200"
                        @click="showAbout = false">知道了</button>
                </div>
            </div>
        </div>


    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { readTextFile, readDir, writeTextFile, exists } from '@tauri-apps/plugin-fs';
import { open } from '@tauri-apps/plugin-dialog';
import {
    type ModResourceTable,
    type ResourceTableData,
    type ResourceItem,
    type AppTauriConfig,
} from './types';
import {ResFileInfo} from './resFileInfo';
import JSON5 from 'json5';
import ItemStringPanel from './ItemStringPanel.vue';
import TextPanel from './TextPanel.vue';


const pageTitle = '暗黑破坏神2重制版:地面物品屏蔽MOD编辑器';
const version = 'v1.0.0';
const author = '作者: [凯恩之角]ghostweo';

const showAbout = ref(false);
const aboutText = '用于编辑D2R地面物品软屏蔽规则的可视化工具。支持按原始文本染色规则解析与显示，便于快速调试与预览。';

// 状态管理
const selectedDirectory = ref<string>('');
const selectedDirName = ref<string>('');
const resourceTableData = ref<ResourceTableData>({ mods: [] });
const modsRootExpanded = ref(true);
const appTauriConfig = ref<AppTauriConfig>({
    d2rModsPath: undefined,
    supportedMods: undefined,
    customFiles: undefined
});

// 新增：传递给 ResEditor 的选中资源对象与内容
const currentResourceItem = ref<ResourceItem | undefined>(undefined);

// 引用ItemStringPanel组件
const itemStringPanelRef = ref<InstanceType<typeof ItemStringPanel> | null>(null);

// 控制资源表(左边那个)显示/隐藏
const showResourcePanel = ref(true);

onMounted(async () => {
    await loadAppConfig();
    //如果配置文件中指定了Mods目录，就尝试加载它
    if (appTauriConfig.value.d2rModsPath !== undefined && appTauriConfig.value.d2rModsPath !== '') {
        tryLoadModsDirFromPath(appTauriConfig.value.d2rModsPath);
    }
});

async function loadAppConfig() {
    try {
        const configText = await readTextFile('data/config.json');
        appTauriConfig.value = JSON5.parse(configText);
        console.log('加载配置文件:', appTauriConfig.value);
    } catch (error) {
        console.error('读取配置文件失败:', error);
        alert(`读取配置文件失败: ${error}`);
    }
}

function toggleResourcePanel() {
    showResourcePanel.value = !showResourcePanel.value;
}

/**
 * 处理资源项点击事件
 */
async function handleResourceClick(resource: ResourceItem) {
    try {
        if (currentResourceItem.value?.type === 'ItemStrings') {
            // 关闭ItemStringPanel
            closeItemStringPanelFromParent();
        }
        if (!await confirm(`是否要载入 ${resource.name}？`)) {
            return;
        }
        currentResourceItem.value = resource;
    } catch (error) {
        console.error('读取资源失败:', error);
        alert(`读取 ${resource.name} 失败: ${error}`);
    }
}

// 新增：调用ItemStringPanel组件的closeItemStringPanel方法
function closeItemStringPanelFromParent() {
    if (itemStringPanelRef.value) {
        itemStringPanelRef.value.closeItemStringPanel();
    }
}

/**
 * 选择目录
 */
async function selectDirectory() {
    try {
        const selectedPath = await open({
            directory: true,
            title: '选择游戏目录',
            multiple: false
        });
        if (await tryLoadModsDirFromPath(selectedPath)) {
            return;
        }
    } catch (error) {
        console.error('选择目录失败:', error);
    }
}


async function tryLoadModsDirFromPath(path: string | null): Promise<boolean> {
    if (path !== null && path !== '') {
        console.log('分析目录，以确定是不是有效的Mods位置:', path);
        // 分析目录内容
        if (! await analyzeDirectory(path)) {
            alert('目录Mods分析失败，请检查目录是否正确');
            return false;
        }
        //如果分析成功，就存入状态
        selectedDirectory.value = path;
        selectedDirName.value = getDirectoryName(path);
        console.log("Mods目录加载成功:", selectedDirectory.value, selectedDirName.value);
        //更新配置文件
        if (appTauriConfig.value.d2rModsPath !== path) {
            appTauriConfig.value.d2rModsPath = path;
            await writeTextFile('data/config.json', JSON.stringify(appTauriConfig.value, null, 2));
        }
        return true;
    }
    return false;
}

/**
 * 获取目录名称
 */
function getDirectoryName(path: string): string {
    const normalized = path.replace(/\\/g, '/');
    const segments = normalized.split(/[/\\]/).filter(Boolean);
    return segments[segments.length - 1] || '';
}

/**
 * 分析目录内容
 */
async function analyzeDirectory(dirPath: string): Promise<boolean> {
    try {
        console.log('开始分析目录:', dirPath);

        // 检查是否是 mods 目录
        const dirName = getDirectoryName(dirPath);
        if (dirName.toLowerCase() !== 'mods') {
            console.log(`目录名称不是 'mods'，当前是: ${dirName}`);
            resourceTableData.value = { mods: [] };
            alert(`目录名称不是 'mods'，当前是: ${dirName} ，请选择正确的Mods目录`);
            return false;
        }
        let supportMods = appTauriConfig.value.supportedMods || [];
        console.log('收到支持的Mod:', supportMods);
        // 读取 mods 目录下的子目录
        const entries = await readDir(dirPath);
        const mods: ModResourceTable[] = [];
        for (const entry of entries) {
            if (entry.isDirectory) { // 是目录
                const modName = entry.name;
                if (!supportMods.includes(modName)) {
                    console.log(`Mod ${modName} 不在支持列表中，跳过`);
                    continue;
                }
                console.log(`检查 mod: ${modName}`);
                const modResourceTable: ModResourceTable = {
                    modName,
                    isDirectoryMod: false,
                    mpqEntryExist: false,
                    resources: [],
                    expanded: false
                };
                const modRootPath = `${dirPath}/${modName}`;
                const rootDirEntries = await readDir(modRootPath);
                //这里通过MDK发现另一种情况，不止有{modName}.mpq,还有其他作者放的附属目录
                let foundMpqDirOrFile = false;
                for (const modRootEntry of rootDirEntries) {
                    if (!foundMpqDirOrFile && modRootEntry.name === `${modName}.mpq`) {
                        modResourceTable.mpqEntryExist = true;
                        modResourceTable.isDirectoryMod = modRootEntry.isDirectory;
                        foundMpqDirOrFile = true;
                    }
                    //这里用正则把所有根目录的txt文件都添加到资源表中
                    if (modRootEntry.name.match(/^.*\.txt$/)) {
                        const textFile = new ResFileInfo();
                        textFile.filename = modRootEntry.name;
                        textFile.path = `${dirPath}/${modName}`;

                        modResourceTable.resources.push({
                            name: modRootEntry.name,
                            prefixLabel: '[作者说明]',
                            type: 'TextFile',
                            modName: modName,
                            files: {
                                mod:textFile    //这里的mod是指放在mod里面的一类文件
                            }
                        });
                    }
                }
                if (!foundMpqDirOrFile) {
                    modResourceTable.mpqEntryExist = false;
                    modResourceTable.affixLabel = '[未找到*.mpq文件或目录]'
                }

                if (modResourceTable.isDirectoryMod) {
                    modResourceTable.expanded = false;
                    // 尝试读取 modinfo.json 来获取作者信息
                    try {
                        const modInfoPath = `${dirPath}/${modName}/${modName}.mpq/modinfo.json`;
                        const content = await readTextFile(modInfoPath);
                        const json = JSON5.parse(content);
                        const authorText = json.author ?? '';
                        if (authorText && typeof authorText === 'string') {
                            //modResourceTable.label = `[已读取][作者：${authorText}]`;
                        }
                    } catch (e) {
                        console.log(`无法读取 ${modName} 的 modinfo.json:`, e);
                    }
                    // 构建改mod资源表,这里和上面的可能存在的txt文件放一起,因为txt文件是mod的一部分 
                    modResourceTable.resources.push(...(await buildResourceItemList(dirPath, modName)));
                } else {
                    modResourceTable.affixLabel = `[需解包]`;
                }
                mods.push(modResourceTable);
            }
        }

        resourceTableData.value = { mods };
        console.log('分析完成，找到 mods:', mods.length);
        return true;
    } catch (error) {
        console.error('分析目录失败:', error);
        resourceTableData.value = { mods: [] };
        return false;
    }
}

/**
 * 构建资源表，实际上只有item-names.json与item-runes.json这两个文件
 */
async function buildResourceItemList(basePath: string, modName: string): Promise<ResourceItem[]> {
    const result: ResourceItem[] = [];

    try {
        // 游戏使用中的文件目录：{basePath}/{modName}/{modName}.mpq/Data/Local/Lng/Strings
        const modPath = `${basePath}/${modName}/${modName}.mpq/Data/Local/Lng/Strings`;
        // 模板目录
        const templatePath = `data/template/${modName}/`;

        const entries = await readDir(modPath);

        // 仅保留两个具体文件：item-names.json 与 item-runes.json
        //const targetFiles = new Set(["item-names.json", "item-runes.json"]);

        for (const entry of entries) {
            if (!entry.isDirectory) {
                let label = '';
                switch (entry.name) {
                    case 'item-names.json':
                        label = '[底材]';
                        break;
                    case 'item-runes.json':
                        label = '[符文]';
                        break;
                    default:
                        continue;

                }
                //modFile指游戏mod中应用的文件，会在ItemStringPanel中“应用”时写入
                const modFile = new ResFileInfo();
                modFile.filename = entry.name;
                modFile.path = modPath;
                //这是模板文件，不会修改，始终作为表格的呈现基础
                const templateFile = new ResFileInfo();
                templateFile.filename = entry.name;
                templateFile.path = templatePath;
                
                //这是记录用户修改,即方案文件。从配置中读入这个文件的路径
                const customFile = new ResFileInfo();
                customFile.filename = entry.name;
                const customFileMap = appTauriConfig.value.customFiles?.[modName];
                customFile.path = customFileMap?.[entry.name] || '';

                if (await modFile.exists() && await templateFile.exists()) {
                    result.push({
                        name: entry.name,
                        type: 'ItemStrings',
                        files: {
                            mod:modFile,
                            template:templateFile,
                            custom:customFile,
                        },
                        prefixLabel: label,
                        modName: modName,
                    });
                }

            }
        }
    } catch (e) {
        console.log(`无法读取 ${modName} 的资源文件:`, e);
    }

    return result;
}


/**
 * 切换 Mod 展开状态
 */
function toggleModExpansion(mod: ModResourceTable) {
    mod.expanded = !mod.expanded;
}

</script>

<style scoped>
@import "tailwindcss";
</style>
